package cn.maple.es.service.impl;


import cn.maple.es.domain.BookBean;
import cn.maple.es.repository.ESRepository;
import cn.maple.es.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private ESRepository esRepository;

    //添加到es
    @Override
    public BookBean save(BookBean blog) {
        return esRepository.save(blog);
    }
    //从es删除
    @Override
    public void delete(BookBean blog) {
        esRepository.delete(blog);
    }
    //查询es
    @Override
    public List<BookBean> findAll() {
        Iterable<BookBean> all = esRepository.findAll();
        ArrayList<BookBean> objects = new ArrayList<>();
        all.forEach(bookBean -> objects.add(bookBean));
        return objects;
    }
    //查询单个
    @Override
    public Optional<BookBean> findOne(String id) {
        Optional<BookBean> bookBean = esRepository.findById(id);
        return bookBean;
    }
    //分页查询
    @Override
    public List<BookBean> pageList() {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withPageable(PageRequest.of(0, 1));

        Page<BookBean> page = esRepository.search(builder.build());

        Iterator<BookBean> iterator = page.iterator();
        List<BookBean> list=new ArrayList<>();
        while(iterator.hasNext()){
            list.add(iterator.next());
        }
        return list;
    }

}

